package com.iasku.manager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ksoap2.serialization.SoapObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;

import com.iasku.constant.Constant;
import com.iasku.entity.IaskuCourse;
import com.iasku.entity.IaskuExam;
import com.iasku.entity.IaskuQuestion;
import com.iasku.entity.UserErrorBook;
import com.iasku.entity.UserHomework;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.iaskueleclass_phone.ReturnData;
import com.iasku.loadimg.MyImageLoader;
import com.iasku.util.SoapUtil;
import com.iasku.web.JSONParser;
import com.iasku.web.WebRequest;
import com.iasku.web.XmlParser;

public class DataManager implements IDataManager {
    private static DataManager mDataManager;

    private DataManager() {

    }

    public static DataManager getInstance() {
        if (mDataManager == null) {
            mDataManager = new DataManager();
        }
        return mDataManager;
    }

    @Override
    public ReturnData<String> login(String username, String password, String schoolid) {
        ReturnData<String> data = new ReturnData<String>();
        Map<String, String> params = new HashMap<String, String>();
        params.put("sid", schoolid);
        params.put("username", username);
        params.put("password", password);
        try {
            SoapObject res = SoapUtil.getResponseSoapObject(params, Constant.METHOD_LOGIN, Constant.NAMESPACE2,
                    Constant.URL2);
            String value = res.getProperty(Constant.METHOD_LOGIN + Constant.RESULT).toString();
            if ("-1".equals(value)) {
                data.status = 0;
                data.msg = "学校代码或用户名不存在";
            } else if ("0".equals(value)) {
                data.status = 1;
                data.msg = "密码错误";
            } else {
                data.status = 2;
                data.msg = "登录成功";
                data.setData(value);
            }
        } catch (Exception e) {
            data.status = -1;
            data.msg = Constant.NETWORK_ERROR;
        }

        return data;
    }

    @Override
    public ReturnData<String> getSchoolInfo(String schoolid) {
        ReturnData<String> data = new ReturnData<String>();
        Map<String, String> params = new HashMap<String, String>();
        params.put("sid", schoolid);
        try {
            SoapObject res = SoapUtil.getResponseSoapObject(params, Constant.METHOD_GETSCHOOLINFO, Constant.NAMESPACE2,
                    Constant.URL2);
            String value = res.getProperty(Constant.METHOD_GETSCHOOLINFO + Constant.RESULT).toString();
            data.status = 1;
            data.setData(value);
        } catch (Exception e) {
            data.status = -1;
            data.msg = Constant.NETWORK_ERROR;
        }
        return data;
    }

    @Override
    public ReturnData<List<UserHomework>> getMyHomework(String iaskuusername, int subjectid, int status,
            String start_time, String end_time, SharedPreferences pref) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("username", iaskuusername);
        params.put("subjectname", String.valueOf(subjectid));
        params.put("status", String.valueOf(status));
        params.put("time1", start_time);
        params.put("time2", end_time);
        String result = WebRequest.postResultByUrl(Constant.METHOD_GETMYHOMEWORK, params);
        return JSONParser.getHomeworkData(status, result, pref);
    }

    @Override
    public ReturnData<ArrayList<UserErrorBook>> getErrorQuestion(String iaskuuername, int subjectid, String start_time,
            String end_time) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("username", iaskuuername);
        params.put("subjectname", String.valueOf(subjectid));
        params.put("time1", start_time);
        params.put("time2", end_time);
        String result = WebRequest.postResultByUrl(Constant.METHOD_GETERRORQUESTION, params);
        ReturnData<ArrayList<UserErrorBook>> mReturnData = JSONParser.getErrorQuestionData(result);
        return mReturnData;
    }

    @Override
    public ReturnData<IaskuExam> getExam(Context mContext, String examid) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("eid", examid);
        String result = WebRequest.postResultByUrl(Constant.METHOD_GETEXAM, params);
        ReturnData<IaskuExam> mReturnData = JSONParser.getExam(mContext, result);
        return mReturnData;
    }

    @Override
    public void getUserAnswer(String iaskuusername, String examid, String questiono, IaskuQuestion iQuestion) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("username", iaskuusername);
        params.put("eid", examid);
        params.put("questionno", questiono);
        String result = WebRequest.postResultByUrl(Constant.METHOD_GETUSERANSWER, params);
        JSONParser.getUserAnswer(iQuestion, result);
    }

    @Override
    public void getQuestionById(IaskuQuestion iQuestion) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("ifall", "0");
        params.put("questionno", iQuestion.getQuestionno());
        SoapObject res = SoapUtil.getResponseSoapObject(params, Constant.METHOD_GETQUESTIONBYID, Constant.NAMESPACE3,
                Constant.URL3);
        String result = res.getProperty(Constant.METHOD_GETQUESTIONBYID + Constant.RESULT).toString();
        XmlParser.getQuestionById(result, iQuestion);
    }

    @Override
    public ReturnData<String> submitUserAnswer(String username, String eid, String questionno, String useranswer,
            String isattach, String maxgrade, int questiontypeid, int subjectnameid, int isright) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", username);
        params.put("eid", eid);
        params.put("questionno", questionno);
        params.put("answer", useranswer);
        params.put("isattach", isattach);
        params.put("maxgrade", maxgrade);
        params.put("questiontype", String.valueOf(questiontypeid));
        params.put("subjectname", String.valueOf(subjectnameid));
        params.put("isright", String.valueOf(isright));
        String result = WebRequest.postResultByUrl(Constant.METHOD_SUMITUSERANSWER, params);
        return JSONParser.submitUserAnswer(result);
    }

    @Override
    public String submitExam(String username, String eid) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", username);
        params.put("eid", eid);
        String result = WebRequest.postResultByUrl(Constant.METHOD_SUBMITEXAM, params);
        return JSONParser.submitExam(result);
    }

    @Override
    public void uploadJpg(String username, String eid, String answerid, String xh, String ss) {
        submitAnswerAttach(username,eid,answerid,xh);
        uploadPic(answerid,xh,ss);
    }

    private void uploadPic(String answerid,String xh, String ss) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("filename", answerid + "_" + xh + ".jpg");
        params.put("ss", ss);
        WebRequest.postResultByUrl(Constant.METHOD_UPLOADJPG, params);
    }

    private void submitAnswerAttach(String username, String eid, String answerid, String xh) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("answerid",answerid);
        params.put("xh", xh);
        params.put("username", username);
        params.put("eid", eid);
        WebRequest.postResultByUrl(Constant.METHOD_SUBMITANSWERATTACH, params);
    }

    @Override
    public ReturnData<Bitmap> loadSubmitImage(Context mContext,String loadPath,String answerid) {
        MyImageLoader loader = new MyImageLoader(mContext);
        loader.setSaveDir("/" + answerid + "/");
        Bitmap bmp = loader.loadSubmitImage(loadPath);
        ReturnData<Bitmap> mData = new ReturnData<Bitmap>();
        if(bmp != null){
            mData.setData(bmp);
        }
        return mData;
    }

    @Override
    public ReturnData<String> submitErrorUserAnswer(String username, String eid, String questionno, String useranswer,
            String isattach, String maxgrade, int questiontypeid, int subjectnameid, int isright, int times) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", username);
        params.put("eid", eid);
        params.put("questionno", questionno);
        params.put("answer", useranswer);
        params.put("isattach", isattach);
        params.put("maxgrade", maxgrade);
        params.put("questiontype", String.valueOf(questiontypeid));
        params.put("subjectname", String.valueOf(subjectnameid));
        params.put("isright", String.valueOf(isright));
        params.put("times", String.valueOf(times));
        String result = WebRequest.postResultByUrl(Constant.METHOD_SUMITUSERANSWER, params);
        return JSONParser.submitUserAnswer(result);
    }

    @Override
    public void startSystemRecommand(String eid,String questionno,String q_score,int q_type_id) {
        HashMap<String, String> t_map = getExamTeacher(eid);
        HashMap<String, String> q_map = getRandomQuestion(questionno);
        try {
            saveHomework(t_map, q_map,q_score,q_type_id);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    private static HashMap<String, String> getExamTeacher(String eid){
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("eid", eid);
        String result = WebRequest.postResultByUrl(Constant.METHOD_GETEXAMTEAHCER, params);
        return JSONParser.getExamTeacher(result);
    }
    
    private static HashMap<String, String> getRandomQuestion(String questionno){
        String methodname = "autorecommendquestion";
        StringBuffer buf = new StringBuffer();
        buf.append("?question_id=").append(questionno);
        String params_string = buf.toString();
        String result = WebRequest.getResultByUrlAjax("http://test1.iasku.net/", params_string, methodname);
        return JSONParser.autorecommendquestion(result);
    }
    
    private static void saveHomework(HashMap<String, String> t_map,HashMap<String, String> q_map,
                    String q_score,int q_type_id) throws Exception {
        String methodname = "SaveHomework";
        if(!t_map.isEmpty() && !q_map.isEmpty()){
            Map<String,String> params = new HashMap<String, String>();
            params.put("username", t_map.get("teachername"));
            params.put("grade", t_map.get("grade_id"));
            params.put("subject", t_map.get("subject_id"));
            params.put("paper_name","系统推荐(" + q_map.get("knowpoint_text_new")+")");
            params.put("end_time", String.valueOf(new Date().getTime() / 1000));
            params.put("questions", q_map.get("question_no_new")+ "_" + q_score + "_" + q_type_id);
            params.put("students", Constant.USER_IASKUNAME);
            params.put("recommend", "1");
            WebRequest.postResultByUrl(methodname, params);
        }
    }

    @Override
    public ReturnData<List<IaskuCourse>> getCourses(String iaskuusername,String subjectname,String time_start_text,String time_end_text) {
        ArrayList<String> classIds = getClassByUsername(iaskuusername);
        if(classIds != null && !classIds.isEmpty()){
           return getCourseByClass(classIds,subjectname,time_start_text, time_end_text);
        }else{
            List<IaskuCourse> courses = new ArrayList<IaskuCourse>();
            ReturnData<List<IaskuCourse>> mData = new ReturnData<List<IaskuCourse>>();
            mData.setData(courses);
            return mData;
        }
    }
    
    private ReturnData<List<IaskuCourse>> getCourseByClass(ArrayList<String> classIds, String subjectname,
            String time_start_text, String time_end_text) {
        ReturnData<List<IaskuCourse>> mReturnData = new ReturnData<List<IaskuCourse>>();
        List<IaskuCourse> courses = new ArrayList<IaskuCourse>();
        for (int i = 0; i < classIds.size(); i++) {
            String methodname = "GetCourseByClass";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("classid", classIds.get(i));
            params.put("classname", "");
            params.put("subjectname", subjectname);
            params.put("btime", time_start_text);
            params.put("endtime", time_end_text);
            System.out.println(params);
            SoapObject res = SoapUtil.getResponseSoapObject(params, methodname, Constant.NAMESPACE2, Constant.URL2);
            XmlParser.getCoursorByClassId(courses,res.getProperty(methodname + Constant.RESULT).toString());
        }
        System.out.println("course=>" + courses.size());
        mReturnData.setData(courses);
        return mReturnData;
    }

    private ArrayList<String> getClassByUsername(String iaskuusername){
        String methodname = "GetClassByUsername";
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", iaskuusername);
        String result = WebRequest.postResultByUrl(methodname, params);
        return JSONParser.getClassesByUsername(result);
    }
}
